/* 写一个函数把obj变成obj2 */
let obj = {
    A: 1,
    "B.C": 2,
    "C.DD.E": 2,
};

let obj2 = {
    A: 1,
    B: {
        C: 2,
    },
    C: {
        DD: {
            E: 2,
        },
    },
};

// 不使用递归
const change = (obj) => {
    let res = {}; //最后返回的对象
    const keyArray = Object.keys(obj); //将key变为数组，be like ['A','B.C','C.DD.E']
    const valArray = Object.values(obj); // 将值变为数组，be like ['1','2','2']
    const nameList = keyArray.map((item) => item.split(".")); // 将key按.分为数组，be like [['A'],['B','C'],['C','DD','E']]
    nameList.forEach((keysArr, index) => {
        let str = {}; //保存每一个属性对象
        const lastKey = keysArr.pop(); //从后往前遍历key，以便生成对象
        str[lastKey] = valArray[index]; // {A:1}
        let prevKey = lastKey; //记录要删除的key
        //如果有多层嵌套，会进入下面循环
        while (keysArr.length) {
            const chKey = keysArr.pop();
            str[chKey] = { ...str }; // {B:{C:1}}
            delete str[prevKey]; //这里要删除原有的{C:1}
            prevKey = chKey; //记录下次循环要删除的key
        }
        res = { ...res, ...str };
    });
    return res;
};

// 使用递归
const digui = (target, part) => {
    console.log(target, part);
    Object.keys(part).forEach((item) => {
        if (item in target) {
            digui(target[item], part[item]);
        } else {
            target[item] = part[item];
        }
    });
};
const change1 = (obj) => {
    const res = {};
    Object.keys(obj).forEach((keyList, index) => {
        let k = {};
        let propertyObject = k; //精髓的一步！
        keyList.split(".").forEach((aKey, index) => {
            propertyObject[aKey] = {};
            if (index === keyList.split(".").length - 1) {
                propertyObject[aKey] = obj[keyList];
            }
            propertyObject = propertyObject[aKey];
        });
        digui(res, k);
    });
    return res;
};
console.log(change1(obj));